<template>
	<div class="main-container">
		<div class="container">
			<div class="tableBar">
				<label style="margin-right: 10px">菜品名称：</label>
				<el-input v-model="input" placeholder="请填写菜品名称" style="width: 14%" clearable @input="initFun()" @keyup.enter.native="initFun" />
				<label style="margin-right: 10px; margin-left: 20px">菜品分类：</label>
				<el-select v-model="categoryId" style="width: 14%" placeholder="请选择" clearable @change="initFun()">
					<el-option v-for="item in dishList" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
				<label style="margin-right: 10px; margin-left: 20px">售卖状态：</label>
				<el-select v-model="dishStatus" style="width: 14%" placeholder="请选择" clearable @change="initFun()">
					<el-option v-for="item in saleStatus" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
				<div class="normal-btn" @click="getList(true)">查询</div>
				<div class="tableLab">
					<span class="delBut non" @click="deleteHandle('批量', null)">批量删除</span>
					<div class="add_btn" style="margin-left: 15px" @click="addDishtype('add')">+ 新建菜品</div>
				</div>
			</div>

			<el-table v-if="tableData.length" :data="tableData" size="small" stripe class="tableBox" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="50" align="center" />
				<el-table-column prop="name" label="菜品名称" align="center" />
				<el-table-column prop="image" label="图片" align="center">
					<template #default="{ row }">
						<el-image style="width: 80px; height: 40px; border: none; cursor: pointer" :src="row.image">
							<div slot="error" class="image-slot">
								<img src="/@/assets/noImg.png" style="width: auto; height: 40px; border: none" />
							</div>
						</el-image>
					</template>
				</el-table-column>
				<el-table-column prop="categoryName" label="菜品分类" align="center" />
				<el-table-column label="售价" align="center">
					<template #default="scope">
						<span style="margin-right: 10px">￥{{ (scope.row.price.toFixed(2) * 100) / 100 }}</span>
					</template>
				</el-table-column>
				<el-table-column label="售卖状态" align="center">
					<template #default="scope">
						<div class="tableColumn-status" :class="{ stop: String(scope.row.status) === '0' }">
							{{ String(scope.row.status) === '0' ? '停售' : '启售' }}
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="updateTime" label="最后操作时间" align="center" />
				<el-table-column label="操作" width="250" align="center">
					<template #default="scope">
						<el-button type="text" size="small" class="blueBug" @click="addDishtype(scope.row.id)"> 修改 </el-button>
						<el-button type="text" size="small" @click="deleteHandle('单删', scope.row.id)" style="color: orange"> 删除 </el-button>
						<el-button
							type="text"
							size="small"
							class="non"
							:class="{
								startBtn: scope.row.status == '0',
								stopBtn: scope.row.status != '0',
							}"
							@click="statusHandle(scope.row)"
						>
							{{ scope.row.status == '0' ? '启售' : '停售' }}
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<Empty v-else :is-search="isSearch" />
			<div style="width: 100%; display: flex; justify-content: center">
				<el-pagination
					v-if="counts > 10"
					class="pageList"
					:page-sizes="[10, 20, 30, 40]"
					:page-size="pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="counts"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
				<el-pagination
					v-model:current-page="page"
					v-model:page-size="pageSize"
					:page-sizes="[100, 200, 300, 400]"
					layout="total, sizes, prev, pager, next, jumper"
					:total="counts"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { getDishPage, deleteDish, dishStatusByStatus, dishCategoryList } from '/@/api/dish';
import Empty from '/@/components/Empty/index.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';

const router = useRouter();
let input = ref('');
let counts = ref(0);
let page = ref(1);
let pageSize = ref(10);
let checkList = ref<any>([]);
let tableData = ref([]);
let dishState = ref('');
let dishList = ref<any>([]);
let categoryId = ref('');
let dishStatus = ref('');
let isSearch = ref(false);
let saleStatus = [
	{
		value: 0,
		label: '停售',
	},
	{
		value: 1,
		label: '启售',
	},
];

onMounted(() => {
	getList();
	getDishCategoryList();
});

const initFun = () => {
	page.value = 1;
	getList();
};

const getList = async (isSearchFlag?: boolean) => {
	isSearch.value = isSearchFlag as boolean;
	await getDishPage({
		page: page.value,
		pageSize: pageSize.value,
		name: input.value || undefined,
		categoryId: categoryId.value || undefined,
		status: dishStatus.value,
	})
		.then((res) => {
			if (res.code === 1) {
				tableData.value = res.data && res.data && res.data.records;
				counts.value = Number(res.data.total);
			}
		})
		.catch((err) => {
			ElMessage.error('请求出错了：' + err.message);
		});
};

// 添加
const addDishtype = (st: string) => {
	if (st === 'add') {
		router.push({ path: '/dish/add' });
	} else {
		router.push({ path: '/dish/add', query: { id: st } });
	}
};

// 删除
const deleteHandle = (type: string, id: any) => {
	if (type === '批量' && id === null) {
		if (checkList.value.length === 0) {
			return ElMessage.error('请选择删除对象');
		}
	}
	console.log(checkList.value.join(','));

	ElMessageBox.confirm('确认删除该菜品, 是否继续?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		deleteDish(type === '批量' ? checkList.value.join(',') : id)
			.then((res) => {
				if (res.code === 1) {
					ElMessage.success('删除成功！');
					getList();
				} else {
					ElMessage.success(res.msg);
				}
			})
			.catch((err) => {
				ElMessage.error('请求出错了：' + err.message);
			});
	});
};

//获取菜品分类下拉数据
const getDishCategoryList = () => {
	dishCategoryList({
		type: 1,
	}).then((res) => {
		if (res && res.data && res.code === 1) {
			dishList.value = res.data.map((item: any) => {
				return { value: item.id, label: item.name };
			});
		}
	});
};

//状态更改
const statusHandle = (row: any) => {
	const params: any = {};
	if (typeof row === 'string') {
		if (checkList.value.length === 0) {
			ElMessage.error('批量操作，请先勾选操作菜品！');
			return false;
		}
		params.id = checkList.value.join(',');
		params.status = row;
	} else {
		params.id = row.id;
		params.status = row.status ? '0' : '1';
	}
	dishState.value = params;
	console.log();

	ElMessageBox.confirm('确认更改该菜品状态?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		// 起售停售---批量起售停售接口
		dishStatusByStatus(dishState.value)
			.then((res) => {
				if (res && res.data && res.code === 1) {
					ElMessage.success('菜品状态更改成功！');
					getList();
				} else {
					ElMessage.error(res.msg);
				}
			})
			.catch((err) => {
				ElMessage.error('请求出错了：' + err.message);
			});
	});
};

// 全部操作
const handleSelectionChange = (val: any) => {
	let checkArr: any[] = [];
	val.forEach((n: any) => {
		checkArr.push(n.id);
	});
	checkList.value = checkArr;
};

//每页条数
const handleSizeChange = (val: any) => {
	pageSize.value = val;
	getList();
};

//翻页
const handleCurrentChange = (val: any) => {
	page.value = val;
	getList();
};
</script>
<style lang="scss" scoped>
.el-table-column--selection .cell {
	padding-left: 10px;
}
</style>
